/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.protocol;


/**
 * Provides a serialized list of the connections in the system. The class 
 * performs a variety of utility functions. These include representation of
 * a connection within the connectivity graph of the hosting node as a 
 * connection that would be consistent with another nodes view of the system.
 * @author Shrideep Pallickara
 * $Revision$
 * $Date$
 */

public class Connection implements ProtocolDebugFlags {
  
  private NodeAddress thisNodeAddress, nodeOne, nodeTwo;
  
  private int levelOne, levelTwo, gatewayLevel;

  private ProtocolID connectionId;
  /**
     @param thisNodeAddress - The Node address of the node hosting a specific
     connectivity graph.
     @param nodeOne - Node Address of the first entity of the gateway.
     @param levelOne - The level of nodeOne.
     @param nodeTwo - Node Address of the second entity of the gateway.
     @param levelTwo - The level of nodeTwo.
     @param gatewayLevel - The gateway level
  */
  public Connection(NodeAddress thisNodeAddress, 
		    NodeAddress nodeOne, int levelOne,
		    NodeAddress nodeTwo, int levelTwo,
		    int gatewayLevel,
		    ProtocolID connectionId) {
    this.thisNodeAddress = thisNodeAddress;
    this.nodeOne = nodeOne;
    this.nodeTwo = nodeTwo;
    this.levelOne = levelOne;
    this.levelTwo = levelTwo;
    this.gatewayLevel = gatewayLevel; 
    this.connectionId = connectionId;
  }

  /** This represents an unmarshalling of the connection information that is
      received over the link. 
      @param nodeAddress - The node address of the server node hosting the
      connectivity graph.
      @param connectionBytes - A marshalled stream of bytes representing a 
      connection.
  */
  public Connection(NodeAddress nodeAddress, byte[] connectionBytes) {
    thisNodeAddress = nodeAddress;
    byte[] addressOneBytes = new byte[4];
    byte[] addressTwoBytes = new byte[4];
    int offset =0;
    System.arraycopy(connectionBytes, offset, addressOneBytes, 0, 4);
    nodeOne = new NodeAddress(addressOneBytes);
    offset+=4;
    levelOne = connectionBytes[offset];
    offset++;
    System.arraycopy(connectionBytes, offset, addressTwoBytes, 0, 4);
    nodeTwo = new NodeAddress(addressTwoBytes);
    offset+=4;
    levelTwo = connectionBytes[offset];
    offset++;
    gatewayLevel = connectionBytes[offset];
    offset++;
    byte[] idBytes = new byte[10];
    System.arraycopy(connectionBytes, offset, idBytes, 0, 10);
    connectionId = new ProtocolID(idBytes);
    offset+=10;
  }

  /** Returns the connectionID associated with the connection.
      @return The connctionID for this particular connection
  */
  public ProtocolID getConnectionId() {
    return connectionId;
  }

  /** Returns the first node in the connection
      @return The first node in the connection */
  public NodeAddress getNodeOne() {
    return nodeOne;
  }

  /** Returns the level associated with first node in the connection
      @return The level of the first node in the connection */
  public int getLevelOne() {
    return levelOne;
  }

  /** Returns the second node in the connection
      @return - The second node in the connection*/
  public NodeAddress getNodeTwo() {
    return nodeTwo;
  }
  
  /** Returns the level associated with second node in the connection
      @return The level of the second node in the connection */
  public int getLevelTwo() {
    return levelTwo;
  }
  
  
  /** Returns the level of this gateway. i.e weather this is a level-0 gateway
      or level-1 and so on. 
      @return level - The level of this gateway
  */
  public int getGatewayLevel() {
    return gatewayLevel;
  }

  
  
  /** This is a marshalling of the connection information to be sent over
      a link. However the marshalling varies depending on the kind of link
      that this information is going to be sent over. This is dictated by 
      the rules for the representation of  a connection within the 
      connectivity graph of the hosting node as a connection that would be 
      consistent with another nodes view of the system.
      @param level - The level of the gateway over which this connection
      information needs to be sent over.
      @return A marshalled stream of connection bytes representing the 
      connection, created using the rules alluded earlier.
  */ 
  public byte[] snapshotConnectionInfo(int level) {
    byte[] connectionBytes = new byte[4 /*nodeOne */ + 1 /*levelOne */ + 
				     4 /*nodeTwo */ + 1 /*levelTwo */ +
				     1 /*gatewayLevel*/ + 10 /*ConnectionId*/];
    int offset = 0;
    /** When we are snapshotting connections at level l we are not
	concerned about connections < level l */
    if (level >  gatewayLevel) {
      System.out.println("Connection: Error in creating connection" + 
			 " information ("+  level + ") greater than gateway"+
			 "Level " + gatewayLevel);
    }
    
    if (levelOne < level) {
      int[] address = thisNodeAddress.getAddressInInts();
      /** Create the level "level" address of the node in question. This can
	  be done using the address of the node in question */
      int[] replacementAddress = { address[address.length -1 -level]};
      byte[] addressOneBytes = 
	new NodeAddress(replacementAddress).getAddressInBytes();
      System.arraycopy(addressOneBytes, 0, 
		       connectionBytes, offset, addressOneBytes.length);
      offset += addressOneBytes.length;
      connectionBytes[offset] = (byte) level;
      offset++;
      byte[] addressTwoBytes = nodeTwo.getAddressInBytes();
      System.arraycopy(addressTwoBytes, 0, 
		       connectionBytes, offset, addressTwoBytes.length);
      offset += addressTwoBytes.length;
      connectionBytes[offset] = (byte) levelTwo;
      offset++;
      connectionBytes[offset] = (byte) gatewayLevel;
      offset++;
      System.arraycopy(connectionId.getBytes(), 0,
		       connectionBytes, offset, 10);
      return connectionBytes;
    }

    if (levelTwo < level) {
      int[] address = thisNodeAddress.getAddressInInts();
            
      byte[] addressOneBytes = nodeOne.getAddressInBytes();
      System.arraycopy(addressOneBytes, 0, 
		       connectionBytes, offset, addressOneBytes.length);
      offset += addressOneBytes.length;
      connectionBytes[offset] = (byte) levelOne;
      offset++;
      
      /** Create the level "level" address of the node in question. This can
	  be done using the address of the node in question */
      int[] replacementAddress = { address[address.length - 1- level]};
      byte[] addressTwoBytes = 
	new NodeAddress(replacementAddress).getAddressInBytes();
      System.arraycopy(addressTwoBytes, 0, 
		       connectionBytes, offset, addressTwoBytes.length);
      offset += addressTwoBytes.length;
      connectionBytes[offset] = (byte) level;
      offset++;

      connectionBytes[offset] = (byte) gatewayLevel;
      offset++;
      System.arraycopy(connectionId.getBytes(), 0,
		       connectionBytes, offset, 10);
      return connectionBytes;
    }
    
    
    byte[] addressOneBytes = nodeOne.getAddressInBytes();
    byte[] addressTwoBytes = nodeTwo.getAddressInBytes();
    
    System.arraycopy(addressOneBytes, 0,
		     connectionBytes, offset, addressOneBytes.length);
    offset+= addressOneBytes.length;
    connectionBytes[offset] = (byte) levelOne;
    offset++;
    System.arraycopy(addressTwoBytes, 0,
		     connectionBytes, offset, addressTwoBytes.length);
    offset+= addressTwoBytes.length;
    connectionBytes[offset] = (byte) levelTwo;
    offset++;
    connectionBytes[offset] = (byte) gatewayLevel;  
    offset++;
    System.arraycopy(connectionId.getBytes(), 0,
		     connectionBytes, offset, 10);
    return connectionBytes;
  }
  
  /** A string representation of the connection */
  public String toString() {
    return ("NodeOne -> " + nodeOne + "(" + levelOne +") " +
		       "NodeTwo -> " + nodeTwo + "(" + levelTwo +") " +
		       "GatewayLevel ->" + gatewayLevel);
  }


   /**
     Compares two objects for equality. Returns a boolean that indicates
     whether this object is equivalent to the specified object. This method
     is used when an object is stored in a hashtable.
     @param obj the Object to compare with
     @return true if these Objects are equal; false otherwise.
     @see java.util.Hashtable
  */
  public boolean equals(Object obj) {
    Connection _conn = (Connection)obj;
    NodeAddress _nodeOne = _conn.getNodeOne();
    NodeAddress _nodeTwo = _conn.getNodeTwo();
    int _levelOne = _conn.getLevelOne();
    int _levelTwo = _conn.getLevelTwo();

    if (nodeOne.equals(_nodeOne)) {
      if (nodeTwo.equals(_nodeTwo)) {
	if ( (levelOne == _levelOne) && (levelTwo == _levelTwo) ) {
	  return true;
	}/** check levels */
      }/** id node2=node2 */
    }/* if node1=node1*/
    
    if (nodeOne.equals(_nodeTwo)) {
      if (nodeTwo.equals(_nodeOne)) {
	if ( (levelOne == _levelTwo) && (levelTwo == _levelOne) ) {
	  return true;
	}/** check levels */
      }/** id node2=node1 */
    }/* if node1=node2*/
    
    return false;
  }

  /**
     Generates a hash code for the receiver. This method is supported 
     primarily for hash tables, such as those provided in java.util.
     If two objects are equal (equals(Object) returns true) they must have the 
     same hash code
     @return an integer hash code for the receiver 
  */
  public int hashCode() {
    String stringRep="";
    int[] _addOne = nodeOne.getAddressInInts();
    int[] _addTwo = nodeTwo.getAddressInInts();
    int _valOne=0;
    int _valTwo = 0;
    for (int i=0; i<_addOne.length; i++) {
      _valOne += _addOne[i];
    }

    for (int i=0; i<_addTwo.length; i++) {
      _valTwo += _addTwo[i];
    }

    
    if (levelOne == levelTwo) {
      /** Multiple conns between say {3}(3) and {2}(3) are entirely possible.
	  The >= case addresses that scenario */
      if (_valOne >= _valTwo) {
	stringRep = _valOne + "." + levelOne + "<>" + 
	  _valTwo +  "." + levelTwo;
      } else {
	stringRep = _valTwo + "." + levelTwo + "<>" + 
	  _valOne +  "." + levelOne;
      }
      return stringRep.hashCode();
    }
    
    if (levelOne > levelTwo) {
      stringRep = _valOne + "." + levelOne + "<>" + 
	_valTwo +  "." + levelTwo;
    } else {
      stringRep = _valTwo + "." + levelTwo + "<>" + 
	_valOne +  "." + levelOne;
    }
    
    return stringRep.hashCode();
  }/* end hashCode() */
  
  
  public static void main(String[] args) {
    int[] address = {5,9,3,1};
    
    int[] a5 = {4};
    int[] aSC_2 = {1};
    ProtocolIDFactory idFactory = 
      new ProtocolIDFactory(new NodeAddress(address), (short) 0);
    ProtocolID connectionId = idFactory.getProtocolID();
    Connection c = new Connection(new NodeAddress(address), 
				  new NodeAddress(a5), 1, 
				  new NodeAddress(aSC_2), 0,
				  1, connectionId);
    System.out.println("Connection -> "+ c);
    int level = 1;
    System.out.println("At level " + level +  
		       new Connection(new NodeAddress(address),
				      c.snapshotConnectionInfo(level)));
    
    
  }

}
